package com.heima.behavoir.interceptor;

import com.heima.utils.thread.BehaviorThreadLocalUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 对请求进行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的userId
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            //存入ThreadLocal
            BehaviorThreadLocalUnit.set(Integer.valueOf(userId));
        }
        return true;
    }

    /**
     * 请求结束后进行 清理
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BehaviorThreadLocalUnit.clear();
    }
}
